import com.mongodb.BasicDBObject;
import java.util.HashMap;
import java.util.Map;
 
/**
 *
 * @author Code4LifeVn
 */
public class PhoneBookConverter implements ModelConverter<PhoneBook> {
 
    @Override
    public PhoneBook convertBasicObjectToModel(BasicDBObject object) {
        String _id =  object.getObjectId("_id").toString();
        double mobi = object.getDouble("mobi");
 
        //Get User Info
        BasicDBObject userInfo = (BasicDBObject) ((BasicDBObject) object).get("user");
        String firstName = userInfo.getString("first_name");
        String lastName = userInfo.getString("last_name");
        int age = userInfo.getInt("age");
 
        //Construct UserInfo Object
        PhoneBook.UserInfo userInfoObject = new PhoneBook().new UserInfo();
        userInfoObject.setFirstName(firstName);
        userInfoObject.setLastName(lastName);
        userInfoObject.setAge(age);
 
        //Construct PhoneBook Object
        PhoneBook phoneBook = new PhoneBook();
        phoneBook.setId(_id);
        phoneBook.setMobi(mobi);
        phoneBook.setInfo(userInfoObject);
 
        return phoneBook;
    }
 
    @Override
    public BasicDBObject convertModelToBasicObject(PhoneBook model) {
        //Java 6
        //Map<String, Object> userInfo = new HashMap<String, Object>();
 
        //Only Java 7,
        Map<String, Object> userInfo = new HashMap<>();
        userInfo.put("first_name", model.getInfo().getFirstName());
        userInfo.put("last_name", model.getInfo().getLastName());
        userInfo.put("age", model.getInfo().getAge());
 
        return new BasicDBObject()
                .append("mobi", model.getMobi())
                .append("user", userInfo);
    }
 
}
